package com.hjh.gameforum.controller;

import com.hjh.gameforum.dto.TopicDto;
import com.hjh.gameforum.dto.TopicQueryParem;
import com.hjh.gameforum.dto.UserHomeQueryParem;
import com.hjh.gameforum.entity.Topic;
import com.hjh.gameforum.result.PageResult;
import com.hjh.gameforum.result.Result;
import com.hjh.gameforum.service.TopicService;
import com.hjh.gameforum.vo.TopicVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/topics")
@RequiredArgsConstructor
@Tag(name = "话题管理", description = "话题相关操作")
@Slf4j
public class TopicController {
    private final TopicService topicService;
    private final RedisTemplate<String, Object> redisTemplate; // 更新类型

    @GetMapping
    @Operation(summary = "根据分类ID获取话题分页展示")
    public Result getTopicsByCategoryId(TopicQueryParem topicQueryParem) {
        log.info("获取分类为{}的话题", topicQueryParem);
        String key = "category_" + topicQueryParem.getCategoryId()+"_" + topicQueryParem.getPage()+"_" + topicQueryParem.getPageSize();
        Object cachedObject = redisTemplate.opsForValue().get(key);
        
        if (cachedObject != null) {
            // 直接返回，因为现在Redis配置已支持正确的反序列化
            return Result.success(cachedObject);
        }

        PageResult<TopicVo> topicList = topicService.getTopics(topicQueryParem);
        redisTemplate.opsForValue().set(key, topicList, 60, TimeUnit.MINUTES);
        return Result.success(topicList);
    }

    @PostMapping
    @Operation(summary = "创建话题")
    public Result createTopic(@RequestBody TopicDto topicDto) {
        log.info("创建话题: {}", topicDto);
        topicService.createTopic(topicDto);
        Set<String> keys = redisTemplate.keys("category_" + topicDto.getCategoryId() + "*");
        if (keys != null && !keys.isEmpty()) {
            // 再批量删除
            redisTemplate.delete(keys);
            log.info("删除了 " + keys.size() + " 个键");
        }
        Set<String> keys2 = redisTemplate.keys("category_0_*");
        if (keys != null && !keys.isEmpty()) {
            // 再批量删除
            redisTemplate.delete(keys2);
            log.info("删除了 " + keys.size() + " 个键");
        }
        return Result.success();
    }

    @GetMapping("/hot")
    @Operation(summary = "获取热门话题")
    public Result getHotTopics() {
        log.info("获取热门话题");
        String key = "hot_topics";
        Object cachedObject = redisTemplate.opsForValue().get(key);
        if (cachedObject != null) {
            return Result.success(cachedObject);
        }
        List<TopicVo> topics = topicService.getHotTopics();
        redisTemplate.opsForValue().set(key, topics, 60, TimeUnit.MINUTES);
        return Result.success(topics);
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取话题详情")
    public Result getTopicById(@PathVariable Integer id) {
        log.info("获取ID为{}的话题详情", id);
        String key = "topic_" + id;
        Object cachedObject = redisTemplate.opsForValue().get(key);
        if (cachedObject != null) {
            return Result.success(cachedObject);
        }
        TopicVo topic = topicService.getTopicById(id);
        redisTemplate.opsForValue().set(key, topic, 60, TimeUnit.MINUTES);
        return Result.success(topic);
}


    @PutMapping("/views/{id}")
    @Operation(summary = "话题浏览量+1")
    public Result updateTopicViews(@PathVariable Integer id) {
        log.info("话题ID为{}的浏览量+1", id);
        topicService.updateTopicViews(id);
        return Result.success();
    }

    @PostMapping("/like/{id}")
    @Operation(summary = "点赞话题")
    public Result likeTopic(@PathVariable Integer id,@RequestParam Integer authorId) {
        log.info("用户点赞话题ID为{}", id);
        topicService.likeTopic(id,authorId);
        return Result.success();
    }

    @DeleteMapping("/like/{id}")
    @Operation(summary = "取消点赞话题")
    public Result unlikeTopic(@PathVariable Integer id,@RequestParam Integer authorId) {
        log.info("用户取消点赞话题ID为{}", id);
        topicService.unlikeTopic(id,authorId);
        return Result.success();
    }

    @GetMapping("/like/{id}")
    @Operation(summary = "获取用户是否点赞话题")
    public Result<Boolean> getLikeStatus(@PathVariable Integer id) {
        log.info("获取用户是否点赞话题ID为{}", id);
        boolean likeStatus = topicService.getLikeStatus(id);
        return Result.success(likeStatus);
    }

    @GetMapping("/pinned")
    @Operation(summary = "获取置顶话题")
    public Result getPinnedTopics() {
        log.info("获取置顶话题");
        String key = "pinned_topics";
        Object cachedObject = redisTemplate.opsForValue().get(key);
        if (cachedObject != null) {
            return Result.success(cachedObject);
        }

        List<TopicVo> topics = topicService.getPinnedTopics();
        redisTemplate.opsForValue().set(key, topics, 60, TimeUnit.MINUTES);
        return Result.success(topics);
    }

    @PutMapping("/update")
    @Operation(summary = "编辑话题")
    public Result updateTopic(@Validated @RequestBody TopicDto topicDto) {
        log.info("编辑话题: {}", topicDto);
        topicService.updateTopic(topicDto);
        String key = "topic_" + topicDto.getTopicId();
        redisTemplate.delete(key);
        return Result.success();
    }

    @PutMapping("/status/{id}")
    @Operation(summary = "设置话题状态")
    public Result setTopic(@PathVariable("id") Long topicId, @RequestParam Integer statusId) {
        log.info("设置状态话题ID为{}", topicId);
        topicService.setTopicStatus(topicId, statusId);
        return Result.success();
    }



    @DeleteMapping("/{topicId}")
    @Operation(summary = "删除话题")
    public Result deleteTopic(@PathVariable Long topicId,@RequestParam Long categoryId) {
        log.info("删除话题ID为{}", topicId);
        topicService.deleteTopic(topicId);
        String key = "topic_" + topicId;
        redisTemplate.delete(key);
        Set<String> keys = redisTemplate.keys("category_" + categoryId + "*");
        if (keys != null && !keys.isEmpty()) {
            // 再批量删除
            redisTemplate.delete(keys);
            log.info("删除了 " + keys.size() + " 个键");
        }
        Set<String> keys2 = redisTemplate.keys("category_0_*");
        if (keys != null && !keys.isEmpty()) {
            // 再批量删除
            redisTemplate.delete(keys2);
            log.info("删除了 " + keys.size() + " 个键");
        }
        return Result.success();
    }


    @GetMapping("/userhome")
    @Operation(summary = "获取用户主页话题")
    public Result getUserHomeTopics( UserHomeQueryParem userHomeQueryParem) {
        log.info("获取用户主页话题ID为{}", userHomeQueryParem.getUserId());
        String key = "userhome_" + userHomeQueryParem.getUserId();
        if (redisTemplate.opsForValue().get(key) != null){
            Object cachedValue = redisTemplate.opsForValue().get(key);
            if (cachedValue instanceof PageResult) {
                return Result.success((PageResult<TopicVo>) cachedValue);
            } else {
                return Result.success((List<TopicVo>) cachedValue);
            }
        }
        PageResult<TopicVo> topics = topicService.getUserHomeTopics(userHomeQueryParem);
        redisTemplate.opsForValue().set(key, topics, 60 * 60 * 24, TimeUnit.SECONDS);
        return Result.success(topics);
    }



}
